/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package ly.count.ohos.demo;


import ly.count.ohos.sdk.Countly;
import ly.count.ohos.sdk.CountlyConfig;
import ly.count.ohos.sdk.CrashFilterCallback;
import ly.count.ohos.sdk.DeviceId;
import ly.count.ohos.sdk.ModuleLog;
import ly.count.ohos.sdk.RemoteConfig;

import ohos.aafwk.ability.AbilityPackage;
import ohos.aafwk.content.Intent;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.MatchingSkills;
import ohos.event.notification.NotificationSlot;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Application
 *
 * @since 2021-04-13
 */
public class MyApplication extends AbilityPackage {
    static long applicationStartTimestamp = System.currentTimeMillis();
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, Countly.TAG);

    /**
     * You should use try.count.ly instead of YOUR_SERVER for the line below if you are using Countly trial service
     */
    // private static final String COUNTLY_SERVER_URL = "http://192.168.64.146";
    private static final String COUNTLY_APP_KEY = "c32e82bf42978ecff96775cbc66d8688aea91d34";
    private CommonEventSubscriber commonEventSubscriber;
    private ModuleLog.LogCallback logCallback = new ModuleLog.LogCallback() {
        @Override
        public void logHappened(String logMessage, ModuleLog.LogLevel logLevel) {
            // duplicated countly logs
            final String message = "Countly Duplicate " + logMessage;
            switch (logLevel) {
                case Verbose:
                    HiLog.info(LABEL, message);
                    break;
                case Debug:
                    HiLog.debug(LABEL, message);
                    break;
                case Info:
                    HiLog.info(LABEL, message);
                    break;
                case Warning:
                    HiLog.warn(LABEL, message);
                    break;
                case Error:
                    HiLog.error(LABEL, message);
                    break;
                default:
                    break;
            }
        }
    };
    private String[] certificates = new String[]{
        "MIIGnjCCBYagAwIBAgIRAN73cVA7Y1nD+S8rToAqBpQwDQYJKoZIhvcNAQELBQAwgY8xCzAJ"
            + "BgNVBAYTAkdCMRswGQYDVQQIExJHcmVhd"
            + "GVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1"
            + "NhbGZvcmQxGDAWBgNVBAoTD1NlY3RpZ28"
            + "gTGltaXRlZDE3MDUGA1UEAxMuU2VjdGln"
            + "byBSU0EgRG9tYWluIFZhbGlkYXRpb24gU"
            + "2VjdXJlIFNlcnZlciBDQTAeFw0yMDA2MD"
            + "EwMDAwMDBaFw0yMjA5MDMwMDAwMDBaMBU"
            + "xEzARBgNVBAMMCiouY291bnQubHkwggEi"
            + "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKA"
            + "oIBAQCl9zmATVRwrGRtRQJcmBmA+zc/ZL"
            + "io3YfkwXO2w8u9lnw60J4JpPNn9OnGcxd"
            + "M+sqbXKU3jTdjY4j3yaA6NlWibq2jU2x6"
            + "HT2sS+I5gFFE/6tO53WqjoMk48i3FkyoJ"
            + "DittwtQrVaRGcP8RjJH0pfXaP+JLrLAgg"
            + "HuW3tCFqYzkWi3uLGVjQbSIRNiXsM3FI0"
            + "UMEa/x1I3U4hLjMjH28KagZbZLWnHOvks"
            + "AvGLg3xQkS+GSQ+6ARZ2/bGh5O9q4hCCC"
            + "k0/PpwAXmrOnWtwrNuwHcCDOvuB22JxLd"
            + "t8jQDYrjwtJIvq4Yut8FQPv/75SKoETWW"
            + "Hyxe0x5NsB34UwA/BAgMBAAGjggNsMIID"
            + "aDAfBgNVHSMEGDAWgBSNjF7EVK2K4Xfpm"
            + "/mbBeG4AY1h4TAdBgNVHQ4EFgQU8uf/ND"
            + "Rt8cu+AwARVIGXPMfxGbQwDgYDVR0PAQH"
            + "/BAQDAgWgMAwGA1UdEwEB/wQCMAAwHQYD"
            + "VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFB"
            + "wMCMEkGA1UdIARCMEAwNAYLKwYBBAGyMQ"
            + "ECAgcwJTAjBggrBgEFBQcCARYXaHR0cHM"
            + "6Ly9zZWN0aWdvLmNvbS9DUFMwCAYGZ4EM"
            + "AQIBMIGEBggrBgEFBQcBAQR4MHYwTwYIK"
            + "wYBBQUHMAKGQ2h0dHA6Ly9jcnQuc2VjdG"
            + "lnby5jb20vU2VjdGlnb1JTQURvbWFpblZ"
            + "hbGlkYXRpb25TZWN1cmVTZXJ2ZXJDQS5j"
            + "cnQwIwYIKwYBBQUHMAGGF2h0dHA6Ly9vY"
            + "3NwLnNlY3RpZ28uY29tMB8GA1UdEQQYMB"
            + "aCCiouY291bnQubHmCCGNvdW50Lmx5MII"
            + "B9AYKKwYBBAHWeQIEAgSCAeQEggHgAd4A"
            + "dQBGpVXrdfqRIDC1oolp9PN9ESxBdL79S"
            + "biFq/L8cP5tRwAAAXJwTJ0kAAAEAwBGME"
            + "QCIEErTN/aGJ8LV9brGklKeGAXMg1EN/F"
            + "UxXDu13kNfXhcAiBrKMYe+W4flPyuLNm5"
            + "jp6FJwtUTZPNpZ+TmM40dRdwjQB0AN+lX"
            + "qtogk8fbK3uuF9OPlrqzaISpGpejjsSwC"
            + "BEXCpzAAABcnBMncsAAAQDAEUwQwIfEYS"
            + "psSDtKpmj9ZmRWsx73G622N74v09JDjzP"
            + "bkg9RQIgUelIqSwqu69JanH7losrqTTsj"
            + "wNv+3QJBNJ6GxJKkh0AdgBvU3asMfAxGd"
            + "iZAKRRFf93FRwR2QLBACkGjbIImjfZEwA"
            + "AAXJwTJ0YAAAEAwBHMEUCIQCMBaaQAoua"
            + "97R+z2zONMUq1XsDP5aoAiutZG4XxuQ6w"
            + "AIgW1p6XS3az4CCqjwbDKxL9qEnw8fWd+"
            + "yLx2skviSsTS0AdwApeb7wnjk5IfBWc59"
            + "jpXflvld9nGAK+PlNXSZcJV3HhAAAAXJw"
            + "TJ1PAAAEAwBIMEYCIQDg1YFbJPPKDIyrF"
            + "ZJ9rtrUklkh2k/wpgwjDuIp7tPtOgIhAL"
            + "dZl9s/qISsFm2E64ruYbdE4HKR1ZJ0zbI"
            + "XOZcds7XXMA0GCSqGSIb3DQEBCwUAA4IB"
            + "AQB2Ar1h2X/S4qsVlw0gEbXO/"
            + "/6Rj8mTB"
            + "4BFW6c5r84n0vTwvA78h003eX00y0ymxO"
            + "i5hkqB8gd1IUSWP1R1ijYtBVPdFi+SsMj"
            + "UsB5NKquQNlWpo0GlFjRlcXnDC6R6toN2"
            + "QixJb47VM40Vmn2g0ZuMGfy1XoQKvIyRo"
            + "sT92jGm1YcF+nLEHBDr+89apZ8sUpFfWo"
            + "AnCom+8sBGwje6zP10eBbprHyzM8snvdw"
            + "o/QNLAzLcvVNKP+Sr4H7HKzec3g1+THI0"
            + "M72TzoguJcOZQEI6Pd+FIP5Xad53rq4jC"
            + "tRGwYrsieH49a3orBnkkJvUKni+mtkxMb"
            + "PTJ7eeMmX9g/0h"
    }; // sample certificate for the countly try server

    @Override
    public void onInitialize() {
        super.onInitialize();

        HashMap<String, String> customHeaderValues = new HashMap<>();
        customHeaderValues.put("foo", "bar");
        Map<String, Object> automaticViewSegmentation = initAutomaticViewSegmentation();
        Map<String, String> metricOverride = new HashMap<>();
        metricOverride.put("SomeKey", "123");
        metricOverride.put("_carrier", "BoneyK");

        initCountlyConfig(customHeaderValues, automaticViewSegmentation);
    }

    private Map<String, Object> initAutomaticViewSegmentation() {
        Map<String, Object> automaticViewSegmentation = new HashMap<>();
        final int textValue1 = 2;
        automaticViewSegmentation.put("One", textValue1);
        final double testValue2 = 4.44d;
        automaticViewSegmentation.put("Three", testValue2);
        automaticViewSegmentation.put("Five", "Six");
        return automaticViewSegmentation;
    }

    private void initCountlyConfig(HashMap<String, String> customHeaderValues,
                                   Map<String, Object> automaticViewSegmentation) {
        String countlyServerUrl = "";
        try {
            countlyServerUrl = getResourceManager().getElement(ResourceTable.String_countly_server_url).getString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        Countly.sharedInstance().setLoggingEnabled(true);
        CountlyConfig config = (new CountlyConfig(this, COUNTLY_APP_KEY, countlyServerUrl))
            .setIdMode(DeviceId.Type.OPEN_UDID)
            // .setDeviceId("67567")
            .enableCrashReporting().setLoggingEnabled(true).setLogListener(logCallback)
            .enableCrashReporting().setViewTracking(true)
            .setAutoTrackingUseShortName(true)
            // .enableTemporaryDeviceIdMode()
            .setRequiresConsent(true).setConsentEnabled(new String[]{
                Countly.CountlyFeatureNames.push, Countly.CountlyFeatureNames.sessions,
                Countly.CountlyFeatureNames.location, Countly.CountlyFeatureNames.attribution,
                Countly.CountlyFeatureNames.crashes, Countly.CountlyFeatureNames.events,
                Countly.CountlyFeatureNames.starRating, Countly.CountlyFeatureNames.users,
                Countly.CountlyFeatureNames.views, Countly.CountlyFeatureNames.apm,
                Countly.CountlyFeatureNames.remoteConfig, Countly.CountlyFeatureNames.feedback
            })
            .addCustomNetworkRequestHeaders(customHeaderValues)
            .setPushIntentAddMetadata(true)
            .setRemoteConfigAutomaticDownload(true, new RemoteConfig.RemoteConfigCallback() {
                @Override
                public void callback(String error) {
                    if (error == null) {
                        HiLog.debug(LABEL, "Automatic remote config download has completed."
                            + Countly.sharedInstance().remoteConfig().getAllValues());
                    } else {
                        HiLog.debug(LABEL, "Automatic remote config download encountered a problem, " + error);
                    }
                }
            })
            .setParameterTamperingProtectionSalt("SampleSalt")
            .setAutomaticViewSegmentation(automaticViewSegmentation)
            .setAutoTrackingExceptions(new Class[]{AbilityExampleCustomEvents.class})
            .setTrackOrientationChanges(true)
            .setRecordAllThreadsWithCrash()
            .setCrashFilterCallback(new CrashFilterCallback() {
                @Override
                public boolean filterCrash(String crash) {
                    return crash.contains("crash");
                }
            })
            .setRecordAppStartTime(true)
            .setHttpPostForced(false)
            .setAppStartTimestampOverride(applicationStartTimestamp)
            // .enableCertificatePinning(certificates)
            // .enablePublicKeyPinning(certificates)
            // .setDisableLocation()
            .setLocation("us", "Böston 墨尔本", "-23.8043604,-46.6718331", "10.2.33.12")
            // .setMetricOverride(metricOverride)
            .setEnableAttribution(true);

        Countly.sharedInstance().init(config);
    }

}
